package czk.concrent.threadpool.threadfactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;

/**
 * DiscardPolicy可能会导致内存溢出
 *
 * @Author:ChenZhangKun
 * @Date: 2023/4/8 15:42
 */
public class DiscardPolicyOutOfMemoryDemo {
    public static void main(String[] args) {
        ThreadPoolExecutor pool = new ThreadPoolExecutor(1, 1, 1, TimeUnit.MINUTES, new ArrayBlockingQueue<>(10),
                new OwnThreadFactory("kd")
                // 这里直接拒绝没有做任何处理
                , new ThreadPoolExecutor.DiscardPolicy());

        List<Future<Integer>> list = new ArrayList<>();
        try {
            Future<Integer> future = pool.submit(() -> {

                System.out.println("xxxx");
                return new Random().nextInt(10);
            });
            // 被拒绝的也会加入集合，导致无法被唤醒
            list.add(future);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        for (Future<Integer> future : list) {
            try {
                // 无法被唤醒，导致被拒绝的会一直阻塞，从而导致list对象无法被回收，future对象一直增多而内存溢出
                System.out.println(future.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    }


}
